﻿using IPR_StudyMeetingMrgSys.Enums;
using IPR_StudyMeetingMrgSys.Extension;
using IPR_StudyMeetingMrgSys.Models;
using IPR_StudyMeetingMrgSys.ViewModel;
using log4net;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Web;
using System.Web.Http;

namespace IPR_StudyMeetingMrgSys.Controllers
{
    public class MessageInfoController : ApiController
    {
        ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        BLL.MessageInfo bll = new BLL.MessageInfo();
        /// <summary>
        /// 消息发布
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/MessageInfo/Add")]
        public IHttpActionResult Add(Model.MessageInfo model)
        {
            log.Info($"MsgTitle:{model.MsgTitle};MsgContent:{model.MsgContent};DepID:{model.DepID};MsgStartTime:{model.MsgStartTime};MsgEndTime:{model.MsgEndTime}");

            ResultMsg resultMsg = new ResultMsg();

            Model.MessageInfo Mol = new Model.MessageInfo();
            Mol.MsgID = new BLL.SysManage().GetMaxId("MessageInfo", "MsgID");
            Mol.MsgTitle = model.MsgTitle;
            Mol.MsgContent = model.MsgContent;
            Mol.MsgAddTime = DateTime.Now;
            Mol.MsgStartTime = model.MsgStartTime;
            Mol.MsgEndTime = model.MsgEndTime;
            Mol.DepID = model.DepID;
            Mol.MsgType = model.MsgType;
            long flag = bll.Add(Mol);
            if (flag > 0)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                resultMsg.Data = flag;
            }
            else
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = "添加失败";
                resultMsg.Data = flag;
            }


            return Json(resultMsg);
        }
        /// <summary>
        /// 获取消息列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("api/MessageInfo/Sel")]
        public IHttpActionResult Sel()
        {
            log.Info($"获取消息列表");
            ResultMsg resultMsg = new ResultMsg();
            DataTable dt = bll.GetList("").Tables[0];
            if (dt.Rows.Count > 0)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                resultMsg.Data = dt;
            }
            else
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                resultMsg.Info = "没有获取到消息信息";
                resultMsg.Data = dt;
            }
            return Json(resultMsg);
        }
        /// <summary>
        /// 删除消息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/MessageInfo/Del")]
        public IHttpActionResult Del(Model.MessageInfo model)
        {
            log.Info($"删除模块");
            ResultMsg resultMsg = new ResultMsg();

            if (bll.Delete(model.MsgID))
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                resultMsg.Data = "";
            }
            else
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                resultMsg.Info = "删除信息失败";
                resultMsg.Data = "";
            }
            return Json(resultMsg);
        }
        /// <summary>
        /// 更新发布消息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/MessageInfo/Edit")]
        public IHttpActionResult Edit(Model.MessageInfo model)
        {
            log.Info($"更新发布消息");
            log.Info($"MsgTitle:{model.MsgTitle};MsgContent:{model.MsgContent};DepID:{model.DepID};MsgStartTime:{model.MsgStartTime};MsgEndTime:{model.MsgEndTime};MsgID:{model.MsgID}");

            ResultMsg resultMsg = new ResultMsg();
            Model.MessageInfo Mol = new Model.MessageInfo();
            Mol.MsgTitle = model.MsgTitle;
            Mol.MsgContent = model.MsgContent;
            Mol.MsgAddTime = DateTime.Now;
            Mol.MsgStartTime = model.MsgStartTime;
            Mol.MsgEndTime = model.MsgEndTime;
            Mol.DepID = model.DepID;
            Mol.MsgID = model.MsgID;
            Mol.MsgType = model.MsgType;
            if (bll.Update(Mol))
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                resultMsg.Data = "";
            }
            else
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                resultMsg.Info = "更新信息失败";
                resultMsg.Data = "";
            }
            return Json(resultMsg);
        }


        #region 主页读取消息
        [HttpGet]
        [Route("api/MessageInfo/Search")]
        public IHttpActionResult Search(string swhere, int page, int limit)
        {
            ResultMsg resultMsg = new ResultMsg();
            try
            {
                swhere = swhere ?? string.Empty;
                int startindex = (page - 1) * limit + 1;
                int endindex = page * limit;
                if (!string.IsNullOrWhiteSpace(swhere))
                {
                    Dictionary<string, string> jsonObject = JsonConvert.DeserializeObject<Dictionary<string, string>>(swhere);
                    swhere = " 1=1 and CHARINDEX('" + LoginUser.DepID + "',DepID,0)>0 ";
                    foreach (var item in jsonObject)
                    {
                        if (item.Key == "MsgTitle")
                        {
                            if ((item.Value != "") && (item.Value != null))
                                swhere += $" AND MsgTitle like '%{item.Value}%' ";
                        }
                    }
                }

                bool blExist = false;
                int rowCount = 0;
                DataSet dsSearch = new IPR_StudyMeetingMrgSys.BLL.MessageInfo().GetListByPage(swhere, "MsgID", startindex, endindex);
                if (dsSearch != null)
                    if (dsSearch.Tables.Count > 0)
                        if (dsSearch.Tables[0].Rows.Count > 0)
                        {
                            //返回token信息
                            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                            resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                            resultMsg.Data = dsSearch.Tables[0];
                            resultMsg.Count = rowCount;
                            blExist = true;
                        }
                if (!blExist)
                {
                    //返回token信息
                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                    resultMsg.Info = "查询结果不存在";
                    resultMsg.Data = null;
                }
            }
            catch (Exception exc)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText() + exc.Message;
                resultMsg.Data = "查询异常！" + exc.Message;
            }
            return Json(resultMsg);
        }


        [HttpGet]
        [Route("api/MessageInfo/GetSingleInfo")]
        public IHttpActionResult GetSingleInfo()
        {
            ResultMsg resultMsg = new ResultMsg();
            try
            {
                string strWhere = string.Empty;
                strWhere= "CHARINDEX('"+LoginUser.DepID+ "',DepID,0)>0 order by MsgAddTime desc ";
                DataTable dt = bll.GetSingleInfo(strWhere).Tables[0];
                resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                resultMsg.Info = "获取最新消息成功";
                resultMsg.Data = dt.Rows.Count > 0 ? dt : null;
                resultMsg.Count = dt.Rows.Count;
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                resultMsg.Info = "获取最新消息失败";
                resultMsg.Data = ex;
            }
            return Json(resultMsg);
        }

        #endregion


        /// <summary>
        /// 获取所在部门所有的最新消息，或者当前部门发布的消息
        /// </summary>
        /// <param name="deptid">要查询的人员的部门号，多个部门时，使用','分隔</param> 
        /// <returns></returns>
        [HttpGet]
        [Route("api/MessageInfo/GetDeptMessage")]
        public IHttpActionResult GetDeptMessage(string deptid)
        {
            log.Info($"获取所在部门最新消息");
            ResultMsg resultMsg = new ResultMsg();
            try
            {
                //string deptid = LoginUser.DepID.ToString();
                string strWhere = string.Empty;
                strWhere = " charindex(','+ltrim(MsgID)+',',','+dbo.GetMsgIDS('"+deptid+ "')+',')>0 and GETDATE()<MsgEndTime  or CurDepID="+deptid;

                DataTable dt = bll.GetList(strWhere).Tables[0];
                resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                resultMsg.Info = "获取最新消息成功";
                resultMsg.Data = dt.Rows.Count > 0 ? dt : null;
                resultMsg.Count = dt.Rows.Count;
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                resultMsg.Info = "获取最新消息失败";
                resultMsg.Data = ex;
            }
            return Json(resultMsg);
        }

        /// <summary>
        /// 获取所在部门最新消息/同时该人员工号未读过的信息
        /// </summary>
        /// <param name="deptid">要查询的人员的部门号，多个部门时，使用','分隔</param>
        /// <param name="empid">员工id</param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/MessageInfo/GetLatestMessage")]
        public IHttpActionResult GetLatestMessage(string deptid,string empid)
        {
            log.Info($"获取所在部门最新消息");
            ResultMsg resultMsg = new ResultMsg();
            try
            {
                string strWhere = string.Empty;
                strWhere = " MsgEndTime>GETDATE() and  a.DepID in (" + deptid + ") and MsgID not in ( select MsgID from MessageReadInfo where EmpID='" + empid + "' )";

                DataTable dt = bll.GetList(strWhere).Tables[0];
                resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                resultMsg.Info = "获取最新消息成功";
                resultMsg.Data = dt.Rows.Count > 0 ? dt : null;
                resultMsg.Count = dt.Rows.Count;
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                resultMsg.Info = "获取最新消息失败";
                resultMsg.Data = ex;
            }
            return Json(resultMsg);
        }
        /// <summary>
        /// 获取所在部门内最近三个月内的消息
        /// </summary>
        /// <param name="deptid">要查询的人员的部门号，多个部门时，使用','分隔</param> 
        /// <returns></returns>
        [HttpGet]
        [Route("api/MessageInfo/GetHistoryMessage")]
        public IHttpActionResult GetHistoryMessage(string deptid)
        {
            log.Info($"获取所在部门内最近三个月内的消息");
            ResultMsg resultMsg = new ResultMsg();
            try
            {
                string strWhere = string.Empty;
                strWhere = " MsgAddTime> DateAdd(M,-3,getdate()) and  a.DepID in (" + deptid + ") ";

                DataTable dt = bll.GetList(strWhere).Tables[0];
                resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                resultMsg.Info = "获取最新消息成功";
                resultMsg.Data = dt.Rows.Count > 0 ? dt : null;
                resultMsg.Count = dt.Rows.Count;
                //if (!LoginUser.IsSuperAdmin)
                //{
                //    strWhere = "DepID=" + LoginUser.UserInfo.DepID;
                //}
                //resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                //resultMsg.Info = "获取最新消息成功";
                //DataTable dt = bll.GetList(1, strWhere, "MsgID desc").Tables[0];
                //resultMsg.Data = dt.Rows.Count > 0 ? bll.DataRowToModel(dt.Rows[0]) : null;
                //resultMsg.Count = dt.Rows.Count;
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                resultMsg.Info = "获取最新消息失败";
                resultMsg.Data = ex;
            }
            return Json(resultMsg);
        }

        [HttpGet]
        [Route("api/MessageReadInfo/MessageReadInfoLog")]
        public IHttpActionResult MessageReadInfoLog(string msgid, string empid)
        {
            log.Info($"消息读取日志");
            ResultMsg resultMsg = new ResultMsg();
            try
            {
                string strWhere = string.Empty;
                strWhere = " MsgID="+msgid+" and EmpID='"+empid+"'";

                bool blExist = false;
                DataSet ds = new BLL.MessageReadInfo().GetList(strWhere);
                if(ds!=null)
                    if(ds.Tables.Count>0)
                        if(ds.Tables[0].Rows.Count>0)
                        {
                            blExist = true;
                        }
                if (!blExist)
                {
                    Model.MessageReadInfo mMsgRI = new Model.MessageReadInfo();
                    mMsgRI.MsgID = Int32.Parse( msgid);
                    mMsgRI.UserID = empid;
                    new BLL.MessageReadInfo().Add(mMsgRI);
                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                    resultMsg.Info = "数据保存成功";  
                }
                else
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                    resultMsg.Info = "数据重复";
                }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                resultMsg.Info = "获取最新消息失败";
                resultMsg.Data = ex;
            }
            return Json(resultMsg);
        }

        /// <summary>
        /// 获取所在部门最新消息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("api/MessageInfo/GetLatestMessageForWelcome")]
        public IHttpActionResult GetLatestMessageForWelcome()
        {
            log.Info($"获取所在部门最新消息");
            ResultMsg resultMsg = new ResultMsg();
            try
            {
                string strWhere = string.Empty;
                if (!LoginUser.IsSuperAdmin)
                {
                    strWhere = "DepID=" + LoginUser.UserInfo.DeptID;
                }
                resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                DataTable dt = bll.GetList(1, strWhere, "MsgID desc").Tables[0];
                resultMsg.Data = dt.Rows.Count > 0 ? bll.DataRowToModel(dt.Rows[0]) : null;
                resultMsg.Count = dt.Rows.Count;
                //resultMsg.Info = "获取最新消息成功";
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }
    }
}
